package com.sgb.kjwl.viewmodel.shopping;

import android.content.Intent;
import android.text.TextUtils;

import androidx.databinding.ObservableField;

import com.chuanglan.shanyan_sdk.OneKeyLoginManager;




import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;

import com.sgb.kjwl.model.entity.AddShoppingCar;
import com.sgb.kjwl.model.entity.ConcreteEntity;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.MaterialCompanyEntity;
import com.sgb.kjwl.model.entity.MaterialDetailEntity;
import com.sgb.kjwl.model.entity.ShopImEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.repository.MaterialRepertory;
import com.sgb.kjwl.view.ui.activity.self.shop.ShopGoodsInfoActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.SetPwdActivity;
import com.sgb.link.utils.Preferences;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import cn.jpush.android.api.JPushInterface;
import io.reactivex.functions.Consumer;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 工程材料列表（1 筛选条件请求 2 列表数据请求）
 */
public class ShopGoodsModel extends BaseViewModel {
    public ObservableField<String> shopImAccount = new ObservableField<>("");
    private ShopGoodsInfoActivity activity;
    private MaterialRepertory repertory;

    public ShopGoodsModel(ShopGoodsInfoActivity activity, MaterialRepertory repertory) {
        this.activity = activity;
        this.repertory = repertory;
    }

    public void getDetailModel(String pid) {
        DialogHelper.showProgressDialog(activity, null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getMaterialAPI().getMaterialDetail(pid).enqueue(new Callback<BaseEntity<MaterialDetailEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<MaterialDetailEntity>> call, Response<BaseEntity<MaterialDetailEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                activity.showProductInfo(response.body().getData());
            }

            @Override
            public void onFailure(Call<BaseEntity<MaterialDetailEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getCompanyModel(String cid) {
        APIManager.getInstance().getMaterialAPI().getMaterialShopDetail(cid).enqueue(new Callback<BaseEntity<MaterialCompanyEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<MaterialCompanyEntity>> call, Response<BaseEntity<MaterialCompanyEntity>> response) {
                if (response.body() == null) return;
                activity.showCompanyInfo(response.body().getData());
            }

            @Override
            public void onFailure(Call<BaseEntity<MaterialCompanyEntity>> call, Throwable t) {

            }
        });
    }

    public String getAreaCode() {
        return repertory.getAreaCode();
    }

    public void addShoppingCar(AddShoppingCar addShoppingCar) {
        DialogHelper.showProgressDialog(activity, null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getShoppingCarNewOrderAPI().addShoppingCar(addShoppingCar).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    MToast.showToast(activity, "加入采购单成功");
                    getCarCount();
                } else {
                    MToast.showToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getCarCount() {
        DialogHelper.showProgressDialog(activity, null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getShoppingCarNewOrderAPI().getCarCount().enqueue(new Callback<BaseEntity<Integer>>() {
            @Override
            public void onResponse(Call<BaseEntity<Integer>> call, Response<BaseEntity<Integer>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getData() == null)
                    return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.refreshCarCount(response.body().getData() == null ? 0 : response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<Integer>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getAuthInfo() {
        DialogHelper.showProgressDialog(activity, null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().getUserInfo().enqueue(new Callback<BaseEntity<UserMsgEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<UserMsgEntity>> call, Response<BaseEntity<UserMsgEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getData() == null) return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if (response.body().getData().isRelevance()) {
                        //企业认证成功
                        getCarCount();
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<UserMsgEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void checkToken(String tag) {
        DialogHelper.showProgressDialog(activity, null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);

        APIManager.getInstance().getShoppingCarAPI().checkToken().enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if ("shopping_car".equals(tag)) {
                        activity.checkTokenView();
                    } else {
                        activity.checkAddTokenView();
                    }
                } else {
                    if (!"Miss_Permission".equals(response.body().getCode())) {
                        activity.toLogin();
                    } else {
                        MToast.showToast(activity, response.body().getMsg());
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getConcreteAttribute(String no) {
        DialogHelper.showProgressDialog(activity, null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);

        APIManager.getInstance().getShoppingCarAPI().getConcreteAttribute(no).enqueue(new Callback<BaseEntity<ConcreteEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<ConcreteEntity>> call, Response<BaseEntity<ConcreteEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.getConcreteSucc(response.body().getData());
                } else {
                    MToast.showToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<ConcreteEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void oneKeyLogin(OneKeyLoginEntity oneKeyLoginEntity) {
        DialogHelper.showProgressDialog(activity, null, "登录中", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().oneClickLogin(oneKeyLoginEntity).enqueue(new Callback<BaseEntity<LoginEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<LoginEntity>> call, Response<BaseEntity<LoginEntity>> response) {

                DialogHelper.dismissProgressDialog();
                if (response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    OneKeyLoginManager.getInstance().finishAuthActivity();
                    if (response.body().getData().isNeedRegister()) {
                        Intent intent = new Intent(activity, SetPwdActivity.class);
                        intent.putExtra("mobile", response.body().getData().getPhone());
                        activity.startActivity(intent);
                    } else {
                        //登录成功逻辑
                        loginImModel(response);

                        /*saveUserInfo(response.body().getData());
                        activity.loginSucceed(response.body().getData(), response.body().getData().getPhone());
                        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
                        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, response.body().getData().getPhone());
                        JPushInterface.setAlias(activity, 1, response.body().getData().getPhone());
                        getUserInfo();*/
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<LoginEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //网易IM登陆
    private void loginImModel(Response<BaseEntity<LoginEntity>> response) {
//        NimUIKit.login(new LoginInfo(response.body().getData().getImAccount(), response.body().getData().getImToken()), new RequestCallback<LoginInfo>() {
//            @Override
//            public void onSuccess(LoginInfo param) {
                DialogHelper.dismissProgressDialog();
                SharedPreferenceUtil.getInstance().cleatData();
                saveUserInfo(response.body().getData());
                MToast.showToast(activity, "登录成功");
                activity.loginSucceed(response.body().getData(), response.body().getData().getPhone());
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, response.body().getData().getPhone());
                JPushInterface.setAlias(activity, 1, response.body().getData().getPhone());
                getUserInfo();
//            }
//
//            @Override
//            public void onFailed(int code) {
//                DialogHelper.dismissProgressDialog();
//            }
//
//            @Override
//            public void onException(Throwable exception) {
//                DialogHelper.dismissProgressDialog();
//            }
//        });
    }

    public void getUserInfo() {
        DialogHelper.showProgressDialog(activity, null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().getUserInfo().enqueue(new Callback<BaseEntity<UserMsgEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<UserMsgEntity>> call, Response<BaseEntity<UserMsgEntity>> response) {
                DialogHelper.dismissProgressDialog();

                if (response.body() == null) return;
                if (response.body().getData() == null) return;
                if (response.body().getState().equals("ok")) {
                    activity.getUserMsgSucceed(response.body().getData());
                } else {
                    MToast.showToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<UserMsgEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //获取商家对应im账户信息
    public void getShopImInfo(String shopId) {
        repertory.getShopImInfo(shopId)
                .subscribe(new Consumer<BaseEntity<ShopImEntity>>() {
                    @Override
                    public void accept(BaseEntity<ShopImEntity> shopImEntityBaseEntity) throws Exception {
                        if (shopImEntityBaseEntity.getState().equals(AppConstant.REQEUST_SECCUESS)) {
                            shopImAccount.set(shopImEntityBaseEntity.getData().getImAccount());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        MLog.d(AppConstant.API_LOG, "error " + throwable.getMessage());
                    }
                });
    }

    private void saveUserInfo(LoginEntity loginEntity) {
        repertory.saveToken(loginEntity.getToken());
        repertory.saveAccount(loginEntity.getPhone());

//        NimUIKit.setAccount(loginEntity.getImAccount());
//        AVChatKit.setAccount(loginEntity.getImAccount());
        //Preferences.saveUserAccount(loginEntity.getImAccount());
 //       Preferences.saveUserToken(loginEntity.getImToken());
    }

}
